﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Level_2.Model;
using System.IO;
using System.Text.RegularExpressions;

public partial class service_feedback : System.Web.UI.Page
{
    TestOnLine_CPS5DAL bll_testOnLine_CPS5 = new TestOnLine_CPS5DAL();
    string fileName = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

        }
    }
    protected void page_error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        if (HttpContext.Current.Server.GetLastError() is HttpRequestValidationException)
        {
            HttpContext.Current.Response.Write("<script>alert('请输入合法的字符串!');window.history.back();</script>");
            HttpContext.Current.Server.ClearError();
        }
    }
    protected void imgbtnOk_Click(object sender, ImageClickEventArgs e)
    {
        TestOnLine_CPS5 model_testOnLine_CPS5 = new TestOnLine_CPS5();
        string userName = "", feedbackContent = "", filePath = "", userEmail = "";
        userName = RegExp.CheckStr(txtUname.Text.Trim());
        feedbackContent = RegExp.CheckStr(txtSuggest.Text.Trim());
        userEmail = RegExp.CheckStr(txtEmail.Text.Trim());
        filePath = flBugImg.PostedFile.FileName;
        if (filePath != "")
        {
            if (CheckUploadFile())
            {
                UploadFile(out filePath);
                lbl_Error.Visible = false;
            }
            else
            {
                lbl_Error.Visible = true;
                return;
            }
        }

        model_testOnLine_CPS5.userName = userName;
        model_testOnLine_CPS5.feedbackContent = feedbackContent;
        model_testOnLine_CPS5.attachmentPath = filePath;
        model_testOnLine_CPS5.UserEmail = userEmail;
        model_testOnLine_CPS5.type = selectT.Value;    //软件名：其他
        int result = bll_testOnLine_CPS5.Add(model_testOnLine_CPS5);

        if (result == 1)
        {
            Response.Write("<script>alert('感谢您提出的宝贵意见！');location.href=location.href</script>");
            txtUname.Text = "";
            txtSuggest.Text = "";
        }
    }
    private bool CheckUploadFile()
    {

        if (isValidatePicture())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    private void AlertError(string errorMessage)
    {
        Response.Write("<script>alert('" + errorMessage + "');return false;</script>");
    }
    private void UploadFile(out string filePath)
    {
        string tag = System.DateTime.Now.ToString("yyyyMMddHHmmSS");
        string fielName = flBugImg.PostedFile.FileName;
        string filePostfix = fielName.Substring(fielName.LastIndexOf("."));
        string serverDictionaryPath = HttpContext.Current.Server.MapPath(@"BugView\");
        if (!System.IO.Directory.Exists(serverDictionaryPath))
        {
            System.IO.Directory.CreateDirectory(serverDictionaryPath);
        }
        filePath = @"BugView\" + txtUname.Text.Trim() + "_" + tag + filePostfix;
        string serverFilePath = HttpContext.Current.Server.MapPath(filePath);
        //uploadBugView1.PostedFile.SaveAs(serverFilePath);

        string error;
        Deliver.AsynchronousClient.StartTranCommand(flBugImg.FileBytes, serverFilePath, out error);

    }

    private bool isValidatePicture()
    {
        //return Regex.IsMatch(strInfo, @"(.gif|.jpg|.jpeg|.GIF|.JPG|.JPEG|.png)");
        bool fileOK = false;
        ///'遍历File表单元素
        HttpFileCollection files = HttpContext.Current.Request.Files;
        /// '状态信息
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
        try
        {
            for (int iFile = 0; iFile < files.Count; iFile++)
            {
                ///'检查文件扩展名字
                HttpPostedFile postedFile = files[iFile];
                string fileExtension;
                fileName = System.IO.Path.GetFileName(postedFile.FileName).ToLower();
                if (fileName != "")
                {
                    fileExtension = System.IO.Path.GetExtension(fileName);
                    String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                    FileExtension[] fe = { FileExtension.BMP, FileExtension.GIF, FileExtension.JPG, FileExtension.PNG };
                    if (fileOK && FileValidation.IsAllowedExtension(flBugImg, fe))
                    {
                        return true;
                    }
                    else
                    {
                        Response.Write("<script>alert('只能上传图片文件!请重新上传');</script>");
                        return false;
                    }
                }
            }
            return true;
        }
        catch (System.Exception Ex)
        {
            Response.Write("<script>alert(" + Ex.Message + ");</script>");
            return false;
        }
    }

    private bool IsEmail(string source)
    {
        if (source == "")
        {
            return false;
        }
        return Regex.IsMatch(source, @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", RegexOptions.IgnoreCase);
    }
    #region //检查图片格式
    public enum FileExtension
    {
        JPG = 255216,
        GIF = 7173,
        BMP = 6677,
        PNG = 13780,
        DOC = 208207,
        DOCX = 8075,
        XLS = 208207,
        XLSX = 8075,
        JS = 239187,
        SWF = 6787,
        TXT = 7067,
        MP3 = 7368,
        WMA = 4838,
        MID = 7784,
        RAR = 8297,
        ZIP = 8075,
        XML = 6063,
        exe = 7790,
        dll = 7790,
        js = 119105,
        html = 6033,
        rar = 8297,
        xml = 6063,
        aspx = 239187,
        cs = 117115,
        txt = 210187,
        sql = 255254
    }
    #endregion

    #region //图片检查
    public class FileValidation
    {
        public static bool IsAllowedExtension(FileUpload fu, FileExtension[] fileEx)
        {
            int fileLen = fu.PostedFile.ContentLength;
            byte[] imgArray = new byte[fileLen];
            fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);
            MemoryStream ms = new MemoryStream(imgArray);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = br.ReadByte();
                fileclass = buffer.ToString();
                buffer = br.ReadByte();
                fileclass += buffer.ToString();
            }
            catch
            {
            }
            br.Close();
            ms.Close();
            foreach (FileExtension fe in fileEx)
            {
                if (Int32.Parse(fileclass) == (int)fe)
                    return true;
            }
            return false;
        }
    }

    #endregion
}